'use strict'

const fs=require('fs')
const router=require('koa-router')();

function getrouter(filepath)
{
    let file=__dirname||filepath
    let objpath=fs.readdirSync(file)
    let res=objpath.filter(item=>{
        return item.endsWith('.js')&& item!='index.js'
    })
    return res
}

function setrouter(router,res){
    res.forEach(item => {
        let file=__dirname+'/'+item
        let obj=require(file)
        for(let key in obj){
            let arr=key.split(' ')
            let rMethod=arr[0]
            let rPath=arr[1]
            let fn=obj[key]
            if(rMethod=='get'){
                router.get(rPath,fn)
            }else if(rMethod=='post'){
                router.post(rPath,fn)
            }else if(rMethod=='put'){
                router.put(rPath,fn)
            }else if(rMethod=='delete'){
                router.delete(rPath,fn)
            }else{
                console.log('请求失败');
            }
        }
    });
    return router.routes();
}

module.exports=function(){
    let file=getrouter(__dirname)
    let fn=setrouter(router,file)
    return fn
}